package com.Cychat.chat.service.impl;

import com.Cychat.chat.entity.VO.FriendVO;
import com.Cychat.chat.mapper.FriendMapper;
import com.Cychat.chat.service.FriendService;
import com.Cychat.commons.entity.pojo.Friend;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.flogger.Flogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Auther: 刘博文
 * Date: 2025/11/7:10:54
 * Description: 好友服务实现类
 */
@Service
public class FriendServiceImpl extends ServiceImpl<FriendMapper, Friend> implements FriendService {
    private static final Logger log = LoggerFactory.getLogger(FriendServiceImpl.class);

    @Autowired
    private FriendMapper friendMapper;

    /**
     * Description : 获取用户的所有好友
     * ChangeLog : 1. 创建 (2025/11/7 10:56 [Esang]);
     *
     * @param userId
     * @return java.util.List<com.Cychat.chat.entity.DTO.FriendDTO>
     */
    @Override
    public List<FriendVO> getAllFriends(Long userId) {
        return friendMapper.selectAllFriendsWithUser(userId);
    }

    /**
     * Description : 发起添加好友
     * ChangeLog : 1. 创建 (2025/11/7 14:18 [Esang]);
     *
     * @param friendId 好友ID
     * @return null
     */
    @Override
    public boolean addFriend(Long userId, Long friendId) {
        Friend friend = new Friend();
        friend.setUserId(userId);
        friend.setFriendUserId(friendId);
        friend.setFriendStatus(0);
        friend.setApplyTime(new Date());
        QueryWrapper<Friend> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("friend_user_id", friendId);
        int update = friendMapper.update(friend, queryWrapper);
        if (update == 1) {
            return false;
        }
        int insert = friendMapper.insert(friend);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    /**
     * Description : 同意好友申请
     * ChangeLog : 1. 创建 (2025/11/7 14:20 [Esang]);
     *
     * @param friendId 好友ID
     * @return null
     */
    @Override
    public boolean agreeFriend(Long userId, Long friendId) {
        try {
            Friend newFriend = new Friend();
            newFriend.setUserId(userId);
            newFriend.setFriendUserId(friendId);
            newFriend.setFriendStatus(1);
            newFriend.setAgreeTime(new Date());
            // 获取好友请求发送时间
            QueryWrapper<Friend> oldQueryWrapper = new QueryWrapper<>();
            oldQueryWrapper.eq("user_id", friendId)
                    .eq("friend_user_id", userId);
            Friend oldFriend = friendMapper.selectOne(oldQueryWrapper);
            if (oldFriend == null) {
                return false;
            }
            newFriend.setApplyTime(oldFriend.getApplyTime());
            // 修改老好友关系状态
            oldFriend.setFriendStatus(1);
            oldFriend.setAgreeTime(newFriend.getAgreeTime());
            int update = friendMapper.update(oldFriend, oldQueryWrapper);
            // 插入新好友关系
            int insert = friendMapper.insert(newFriend);
        } catch (Exception e) {
            log.error("同意好友申请失败");
        }
        return true;
    }

    /**
     * Description : 查看所有好友申请
     * ChangeLog : 1. 创建 (2025/11/7 15:21 [Esang]);
     *
     * @param userId 用户ID
     * @return null
     */
    @Override
    public List<FriendVO> getFriendApply(Long userId) {
        return friendMapper.selectFriendApplyWithUser(userId);
    }

    /**
     * Description : 查看用户收到的所有好友申请记录（包括待处理、已同意、已拒绝）
     * ChangeLog : 1. 创建 (2025/11/8 10:35 [Qoder]);
     *
     * @param userId 用户ID
     * @return null
     */
    @Override
    public List<FriendVO> getAllFriendRequests(Long userId) {
        return friendMapper.selectAllFriendRequestsWithUser(userId);
    }

    /**
     * Description : 删除好友
     * ChangeLog : 1. 创建 (2025/11/7 15:21 [Esang]);
     *
     * @param friendId 好友ID
     * @return null
     */
    @Override
    public boolean deleteFriend(Long userId, Long friendId) {
        QueryWrapper<Friend> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("friend_user_id", friendId)
                .eq("friend_status", 1);
        Friend newFriend = new Friend();
        newFriend.setFriendStatus(3);
        int update = friendMapper.update(newFriend, queryWrapper);
        if (update > 0) {
            return true;
        }
        return false;
    }

    /**
     * Description : 拒绝好友申请
     * ChangeLog : 1. 创建 (2025/11/7 16:16 [Esang]);
     *
     * @param friendId 好友ID
     * @return null
     */
    @Override
    public boolean refuseFriend(Long userId, Long friendId) {
        try {
            QueryWrapper<Friend> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", friendId)
                    .eq("friend_user_id", userId)
                    .eq("friend_status", 0);

            Friend oldfriend = new Friend();
            oldfriend.setFriendStatus(4);
            int update = friendMapper.update(oldfriend, queryWrapper);
            Friend newfriend = new Friend();
            newfriend.setUserId(userId);
            newfriend.setFriendUserId(friendId);
            newfriend.setFriendStatus(2);
            newfriend.setApplyTime(oldfriend.getApplyTime());
            newfriend.setAgreeTime(new Date());
            int insert = friendMapper.insert(newfriend);
        } catch (Exception e) {
            log.error("拒绝好友申请失败:", e);
            return false;
        }
        return true;
    }
}